<template>
  <div v-loading.fullscreen.lock="loading">
    <el-table class="tb-edit" empty-text=" " :data="keywords" size="small" style="width: 680px">
      <el-table-column prop="name" label="标题" />
      <el-table-column prop="value" label="模板参数" width="200">
        <template slot-scope="scope">
          <click-to-edit-input :input="scope.row.value" @change="handleEditValue($event, scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column prop="example" label="example" />
      <el-table-column prop="rule" label="字段说明">
        <template slot-scope="scope">
          {{ ruleMap[scope.row.rule] }}
        </template>
      </el-table-column>
    </el-table>
    <msg-keywords-dialog ref="msgKeywordDialog" />
  </div>
</template>

<script>
import MsgKeywordsDialog from './MsgKeywordsDialog'
import ClickToEditInput from './ClickToEditInput'
import ruleMap from '@/utils/keywordRuleDesc'
import { getTplKeywords } from '@/api/wxTemplateMsg'

export default {
  name: 'TemplateKeywordsConfig',
  components: {
    ClickToEditInput,
    MsgKeywordsDialog
  },
  model: {
    prop: 'keywords',
    event: 'change'
  },
  props: {
    keywords: Array,
    appId: String,
    tid: String
  },
  data() {
    return {
      loading: false,
      ruleMap: ruleMap,
      kidList: [],
      valueMap: {},
      tplKeywordList: false
    }
  },
  methods: {
    handleEditValue(e, $index) {
      const list = [].concat(this.keywords)
      list[$index].value = e
      this.$emit('change', list)
    },
    paddingNum(num, length) {
      for (var len = (num + '').length; len < length; len = num.length) {
        num = '0' + num
      }
      return num
    },
    handleConfig() {
      this.loading = true
      const kidList = []

      for (const i in this.keywords) {
        this.valueMap[this.keywords[i].kid] = this.keywords[i].value || ''
        kidList.push(this.keywords[i].kid)
      }
      getTplKeywords({
        appId: this.appId,
        tid: this.tid
      }).then(res => {
        console.info(res)
        this.loading = false
        this.$refs.msgKeywordDialog.open(res.data, kidList).then(res => {
          for (const i in res) {
            const item = res[i]
            if (this.valueMap[item.kid] !== undefined) {
              item.value = this.valueMap[item.kid]
            } else {
              item.value = '${' + item.rule + this.paddingNum(item.kid, 2) + '}'
            }
          }
          this.$emit('change', res)
        })
      }).catch(res => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
